package com.example.cloud.controller;

import com.example.cloud.common.Result;
import com.example.cloud.dto.VideoInfo;
import com.example.cloud.service.VideoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 视频控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/video")
public class VideoController {

    @Autowired
    private VideoService videoService;

    /**
     * 解析视频链接
     *
     * @param url 视频分享链接
     * @return 解析结果
     */
    @PostMapping("/parse")
    public Result<VideoInfo> parseVideo(@RequestParam String url) {
        if (!StringUtils.hasText(url)) {
            return Result.error("视频链接不能为空");
        }
        
        try {
            VideoInfo videoInfo = videoService.parseVideo(url);
            if (videoInfo != null && StringUtils.hasText(videoInfo.getUrl())) {
                return Result.success(videoInfo);
            } else {
                return Result.error("解析失败，请检查链接是否正确");
            }
        } catch (Exception e) {
            log.error("解析视频失败: {}", e.getMessage(), e);
            return Result.error("解析失败: " + e.getMessage());
        }
    }

    /**
     * 解析视频链接（JSON请求体）
     *
     * @param params 请求参数，包含url字段
     * @return 解析结果
     */
    @PostMapping("/parse/json")
    public Result<VideoInfo> parseVideoJson(@RequestBody Map<String, String> params) {
        String url = params.get("url");
        if (!StringUtils.hasText(url)) {
            return Result.error("视频链接不能为空");
        }
        
        try {
            VideoInfo videoInfo = videoService.parseVideo(url);
            if (videoInfo != null && StringUtils.hasText(videoInfo.getUrl())) {
                return Result.success(videoInfo);
            } else {
                return Result.error("解析失败，请检查链接是否正确");
            }
        } catch (Exception e) {
            log.error("解析视频失败: {}", e.getMessage(), e);
            return Result.error("解析失败: " + e.getMessage());
        }
    }

    /**
     * 获取支持的平台列表
     *
     * @return 支持的平台列表
     */
    @GetMapping("/platforms")
    public Result<Map<String, String>> getSupportedPlatforms() {
        Map<String, String> platforms = new HashMap<>();
        platforms.put("douyin", "抖音");
        platforms.put("kuaishou", "快手");
        platforms.put("xiaohongshu", "小红书");
        platforms.put("weibo", "微博");
        platforms.put("bilibili", "哔哩哔哩");
        return Result.success(platforms);
    }
} 